Your next choice of formatter is the SoapFormatter type, which serializes data in a proper SOAP envelope. In a nutshell, the Simple Object Access Protocol (SOAP) defines a standard process in which you can invoke methods in a platform- and OS-neutral manner.
Assuming you have set a reference to the System.Runtime.Serialization.Formatters.Soap.dll assembly (and imported the System.Runtime.Serialization.Formatters.Soap namespace), you can persist and retrieve a JamesBondCar as a SOAP message simply by replacing each occurrence of BinaryFormatter with SoapFormatter. Consider the following new method of the Program class, which serializes an object to a local file:
// Be sure to import System.Runtime.Serialization.Formatters.Soap // and reference System.Runtime.Serialization.Formatters.Soap.dll. static void SaveAsSoapFormat (object objGraph, string fileName) { // Save object to a file named CarData.soap in SOAP format. SoapFormatter soapFormat = new SoapFormatter(); using(Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { soapFormat.Serialize(fStream, objGraph); } Console.WriteLine("=> Saved car in SOAP format!"); }
As before, you use Serialize() and Deserialize() to move the object graph into and out of the stream. If you call this method from Main() and run the application, you can open the resulting *.soap file. Here you can locate the XML elements that mark the stateful values of the current JamesBondCar, as well as the relationship between the objects in the graph by using the #ref tokens (see Figure 20-6).
Figure 20-6 JamesBondCar serialized using a SoapFormatter